package com.example.service.impl;

import com.example.dao.ChinaAreaRepository;
import com.example.entity.ChinaArea;
import com.example.mapper.ChinaAreaMapper;
import com.example.service.ChinaAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Title: spring-boot-druid
 * @Package com.example.service.impl
 * @Date 2018/5/9下午2:12
 * @Author PX ye
 * @E-mail yepx2013@gmail.com
 * @Company http://www.yiautos.com
 * @Description: ${todo}
 */
@Service
public class ChinaAreaServiceImpl implements ChinaAreaService {

    @Autowired
    private ChinaAreaMapper chinaAreaMapper;

    @Override
    public List<ChinaArea> getChinaAreaAll() {
        System.out.println("进入实现类获取数据！");

        List<ChinaArea> returnList = new ArrayList<>();

        List<ChinaArea> provinceList = chinaAreaMapper.getChinaAreaByNotParentId();
        for(ChinaArea area : provinceList){
            returnList.add(getChinaAreaByParendId(area));
        }
        return returnList;
    }

    @Override
    public ChinaArea getChinaAreaById(Long id) {
        System.out.println(id+"进入实现类获取数据！");

        ChinaArea chinaArea = chinaAreaMapper.getChinaAreaById(id);
        chinaArea = getChinaAreaByParendId(chinaArea);

        return chinaArea;
    }

    /**
     * 递归处理
     * @param chinaArea
     */
    private ChinaArea getChinaAreaByParendId(ChinaArea chinaArea){

        Long parentId = chinaArea.getId();
        List<ChinaArea> childList = chinaAreaMapper.getChinaAreaByParentId(parentId);
        if(!(null == childList || childList.size() == 0)){

            chinaArea.setChildrenList(childList);
            for (ChinaArea child : childList) {
                getChinaAreaByParendId(child);
            }

        }
        return chinaArea;
    }
}
